#!/bin/bash
info() {
    local MESSAGE=$1

    echo -e "\E[34m\n== $MESSAGE\E[00m";
}

usage() {
    echo "Generates CA and RootCA certificates.

usage: $(basename $0) [-h] [-p PREFIX] [-d DIR] FQDN
  -d|--dir:    directory to place output files in
  -p|--prefix: prefix to use for output files
  -h|--help:   prints this help message"
    exit 1
}

generate_certs() {
    local FQDN=$1
    local PREFIX=$2
    local DIR=$3

    TMP=$(mktemp -d)
    function cleanup {
        rm -rf "${TMP}"
    }
    trap cleanup EXIT
    pushd "${TMP}" > /dev/null

    echo "01" > serial
    touch index.txt index.txt.attr
    cat /etc/pki/tls/openssl.cnf | sed "s|/etc/pki/CA|${TMP}|" > openssl.cnf

    info "Creating Root CA certificate for '${FQDN}'"
    openssl req -new -batch -x509 -days 3650 -nodes -newkey rsa:1024 \
        -subj /CN=${FQDN}/C=FR/ST=PACA/L=Aix/O=Eurecom/OU=CM \
        -out ${PREFIX}.cacert.pem \
        -keyout ${PREFIX}.cakey.pem

    info "Generating private key"
    openssl genrsa -out ${PREFIX}.key.pem 1024

    info "Generating self-signed Certificate Signing Request"
    openssl req -new -batch \
        -subj /CN=${FQDN}/C=FR/ST=PACA/L=Aix/O=Eurecom/OU=CM \
        -key ${PREFIX}.key.pem \
        -out ${PREFIX}.csr.pem

    info "Creating CA certificate"
    openssl ca -outdir . -batch -config ./openssl.cnf \
        -in ${PREFIX}.csr.pem \
        -cert ${PREFIX}.cacert.pem \
        -keyfile ${PREFIX}.cakey.pem \
        -out ${PREFIX}.cert.pem

    info "Copying to $DIR"
    chmod g+r *.pem
    mv -t "${DIR}" ${PREFIX}{.cakey.pem,.cert.pem,.cacert.pem,.key.pem}

    popd > /dev/null
}

# parse command line args
POSITIONAL=()
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -h|--help)
        usage
        ;;
        -d|--dir)
        DIR="$2"
        shift 2 # past argument
        ;;
        -p|--prefix)
        PREFIX="$2"
        shift 2 # past argument
        ;;
        *) # unknown option
        POSITIONAL+=("$key") # save it in an array for later
        shift # past argument
        ;;
    esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [ $# -ne 1 ]; then
    usage
fi
FQDN=$1
PREFIX=${PREFIX:-${FQDN%%.*}}
DIR=${DIR:-$(pwd)}

# make destination path absolute (since we're copying from tmpdir later)
if [[ "${DIR}" != /* ]]; then
    DIR=$(pwd)/${DIR}
fi

generate_certs $FQDN $PREFIX $DIR
